package com.zxs.domain.handel.subject;

import com.zxs.common.entity.Result;
import com.zxs.common.enums.SubjectInfoTypeEnum;
import com.zxs.domain.entity.dto.SubjectInfoDTO;
import com.zxs.infra.basic.entity.SubjectMultiple;
import com.zxs.infra.basic.entity.SubjectRadio;
import com.zxs.infra.basic.mapper.SubjectMappingMapper;
import com.zxs.infra.basic.service.SubjectMultipleService;
import com.zxs.infra.basic.service.impl.SubjectMultipleServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 多选的题目的策略类
 * @author zxs
 * @date 2025/11/16 上午4:07
 */
@Component
public class MultipleTypeHandel implements SubjectTypeHandel{

    @Autowired
    private SubjectMultipleServiceImpl subjectMultipleService;

    @Autowired
    private SubjectMappingMapper subjectMappingMapper;

    @Override
    public SubjectInfoTypeEnum getHandelType() {
        return SubjectInfoTypeEnum.MULTIPLE;
    }

    @Override
    public Result add(SubjectInfoDTO subjectInfoDTO) {
        //多选题目的插入
        Result<Object> result = new Result<>();
        List<SubjectMultiple> subjectMultiples = new ArrayList<>();
        //单选题目的插入
        if (CollectionUtils.isEmpty(subjectInfoDTO.getSubjectAnswerDTOS())) {
            result = Result.failed("选项不能为空！");
            return result;
        }
        subjectInfoDTO.getSubjectAnswerDTOS().forEach(option -> {
            SubjectMultiple subjectMultiple = new SubjectMultiple();
            BeanUtils.copyProperties(option, subjectMultiple);
            subjectMultiple.setSubjectId(subjectInfoDTO.getId());
            subjectMultiples.add(subjectMultiple);
        });
        Integer i = subjectMultipleService.batchInsert(subjectMultiples);
        if (i == subjectMultiples.size()) {
            result =Result.success("插入单选题成功");
            return result;
        }
        return null;
    }

    @Override
    public SubjectInfoDTO query(int subjectId) {
        SubjectInfoDTO subjectInfoDTO = new SubjectInfoDTO();
        List<String> subjectAnswers = new ArrayList<>();
        //查找正确答案
        List<SubjectMultiple> subjectMultiples = subjectMultipleService.queryBySubjectId(subjectId);
        subjectMultiples.forEach(subjectMultiple -> {
            subjectAnswers.add(subjectMultiple.getOptionContent());
        });
        String joinedAnswers = String.join(",", subjectAnswers);
        subjectInfoDTO.setSubjectAnswer(joinedAnswers);
        List<String> labelNames = subjectMappingMapper.selectLabelNames(subjectId);
        subjectInfoDTO.setLabelNames(labelNames);
        return subjectInfoDTO;
    }
}